package cn.com.youjile.handler;

import cn.com.youjile.entity.MsgInfo;
import cn.com.youjile.observer.MsgSubject;
import cn.com.youjile.server.GeneralServer;
import cn.com.youjile.utils.MsgInfoFactory;
import cn.com.youjile.utils.MsgNumUtil;
import cn.com.youjile.utils.ResultUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe
 */
public class GeneralServerHandler extends SimpleChannelInboundHandler<MsgInfo> {

    private static final Logger logger = LoggerFactory.getLogger(GeneralServerHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MsgInfo msg){
        logger.debug("server recieved : ctx = [" + ctx + "], msg = [" + msg.toString() + "]");
        try{  //对所有消息进行异常捕获，防止用户逻辑影响整个server的运行
            MsgSubject.getInstance().setState(ctx, msg);
        } catch (Exception e) {
            e.printStackTrace();
            String s = "处理消息异常：" + e.getMessage();
            logger.error(s);
            Channel channel = ctx.channel();
            if(channel != null && channel.isOpen()){
                byte[] result = ResultUtil.error("处理消息异常");
                msg.setInfo(result);
                channel.writeAndFlush(msg);
            }
        }
    }

    /**
     * channel处于active时，这个方法被执行
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx){
        logger.debug("channel active ：" + ctx );
    }

    /**
     * channel处于inactive时，这个方法被执行
     * @param ctx
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        logger.debug("channel inactive ：" + ctx);
    }

    /**
     * 客户第一次连接上来时执行本方法
     * @param ctx
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx){
        logger.info("建立连接，handlerAdded添加handler ：" + ctx);
        GeneralServer.allChannels.add(ctx.channel());
        //响应消息
        byte[] success = ResultUtil.success();
        MsgInfo msg = MsgInfoFactory.buildMessageInfo(MsgNumUtil.success, success);
        ctx.writeAndFlush(msg);
    }

    /**
     * 客户端异常或者正常断开连接时执行本方法
     * @param ctx
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx){
        dealHandlerRemoved(ctx);
    }

    public synchronized void dealHandlerRemoved(ChannelHandlerContext ctx){
        Channel channel = ctx.channel();
        logger.info("断开连接，移除hendler ：" + ctx);
        /**
         * 这里可以添加断开连接时的具体业务逻辑
         */
        if(GeneralServer.allChannels.contains(channel)) {
            GeneralServer.allChannels.remove(channel);
        }
        try {
            super.handlerRemoved(ctx);
        } catch (Exception e) {
            logger.error("断开连接，移除hendler异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        logger.debug("ctx = [" + ctx + "], evt = [" + evt + "]");
    }

}
